package com.picshare.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.picshare.model.ApiKey;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ApiService {
    
    @Value("${app.data.dir}")
    private String dataDir;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private File apiKeyFile;
    private List<ApiKey> apiKeys = new ArrayList<>();
    
    @PostConstruct
    public void init() {
        createDataDirectory();
        apiKeyFile = new File(dataDir, "apikeys.json");
        loadApiKeys();
    }
    
    private void createDataDirectory() {
        try {
            Files.createDirectories(Paths.get(dataDir));
        } catch (IOException e) {
            System.err.println("创建数据目录失败: " + e.getMessage());
        }
    }
    
    private void loadApiKeys() {
        if (apiKeyFile.exists()) {
            try {
                ApiKey[] keyArray = objectMapper.readValue(apiKeyFile, ApiKey[].class);
                apiKeys.clear();
                for (ApiKey key : keyArray) {
                    apiKeys.add(key);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private void saveApiKeys() {
        try {
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(apiKeyFile, apiKeys);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public ApiKey createApiKey(String username, String description) {
        ApiKey apiKey = new ApiKey(username, description);
        apiKeys.add(apiKey);
        saveApiKeys();
        return apiKey;
    }
    
    public boolean validateApiKey(String key) {
        Optional<ApiKey> apiKeyOpt = apiKeys.stream()
            .filter(k -> k.isActive() && k.getKey().equals(key))
            .findFirst();
        
        if (apiKeyOpt.isPresent()) {
            ApiKey apiKey = apiKeyOpt.get();
            apiKey.setLastUsed(System.currentTimeMillis());
            saveApiKeys();
            return true;
        }
        return false;
    }
    
    public boolean revokeApiKey(String key) {
        Optional<ApiKey> apiKeyOpt = apiKeys.stream()
            .filter(k -> k.getKey().equals(key))
            .findFirst();
        
        if (apiKeyOpt.isPresent()) {
            ApiKey apiKey = apiKeyOpt.get();
            apiKey.setActive(false);
            saveApiKeys();
            return true;
        }
        return false;
    }
    
    public List<ApiKey> getUserApiKeys(String username) {
        return apiKeys.stream()
            .filter(k -> k.getUsername().equals(username))
            .collect(Collectors.toList());
    }
    
    public List<ApiKey> getAllApiKeys() {
        return new ArrayList<>(apiKeys);
    }
    
    public ApiKey getApiKeyInfo(String key) {
        return apiKeys.stream()
            .filter(k -> k.getKey().equals(key) && k.isActive())
            .findFirst()
            .orElse(null);
    }
    
    public boolean deleteApiKey(String key) {
        boolean removed = apiKeys.removeIf(k -> k.getKey().equals(key));
        if (removed) {
            saveApiKeys();
        }
        return removed;
    }
}